package com.dianshang.controller.auth;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dianshang.pojo.system.LoginLog;
import com.dianshang.service.system.LoginLogService;
import com.dianshang.utils.WebUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 登录成功处理器(组件)
 */
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @Reference
    private LoginLogService loginLogService;

    /**
     * 登录日志处理
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        // 登录成功后的处理
        System.out.println("登录成功了，我要在这里记录日志"); // 登录成功后会调用
        String name = authentication.getName(); // 当前登录用户
        String ip = request.getRemoteAddr(); // 获取访问的ip

        LoginLog loginLog = new LoginLog();
        loginLog.setLoginName(name);
        loginLog.setIp(ip);
        loginLog.setBrowserName(WebUtil.getBrowserName(request.getHeader("user-agent"))); // 获取浏览器名称
         loginLog.setLocation(WebUtil.getCityByIP(ip)); // 保存地区/城市信息
        loginLog.setLoginTime(new Date()); // 当前登录时间
        loginLogService.insert(loginLog);
        // 转发(服务器行为)到main.html页面
        request.getRequestDispatcher("/main.html").forward(request,response);
    }

}